/*
 * Copyright (c) 2017, 1DAOYUN and/or its affiliates. All rights reserved.
 * 1DAOYUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.iot.nev.gateway.collector.tcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import com.iot.nev.gateway.server.GatewayServer;

/**
 * 
 * TCP 实现方式。 接收数据，解密转码，转发。
 * 
 * @author Song Xueyong
 *
 */
public class NettyTCPServerHandler extends SimpleChannelInboundHandler<Object> {

	// logger
	private Logger logger = Logger.getLogger(NettyTCPServerHandler.class);

	/** Gateway */
	private static GatewayServer gateway;

	/**
	 * Create Server.
	 * 
	 * @param gateway
	 */
	public NettyTCPServerHandler() { 
		if(gateway == null){
			gateway = new GatewayServer();
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.warn("## Unexpected exception from downstream.", cause);
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("## Begin to Collect Message:" + msg);
		// 原始信息 解密码64
		// 这里先简单处理，直接转换成字符串，继续向下传递
		// String message = decodeData(msg.toString());
		// TODO: Netty协议结项(MQTT on TCP/UDP)
		// 交给路由器进行转发(kafka)
		// gateway.getRouter().publish(message);
		// 反馈给客户端
		ctx.channel().writeAndFlush("## Server Accessed Successful!\n");
		// 释放消息
		ReferenceCountUtil.release(msg);
		// logger.info("## Finish Collecting Message:" + message);
	}

	/**
	 * 对给定的字符串进行base64解码操作
	 */
	public String decodeData(String inputData) {
		try {
			if (null == inputData) {
				return null;
			}
			return new String(Base64.decodeBase64(inputData.getBytes("UTF-8")), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error(inputData, e);
		}
		return null;
	}
}